<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 输入框和按钮区域 -->
    <el-card shadow="hover">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList()"
            @change="getUserList()"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList()"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <!-- 数据显示区域 -->
      <el-table :data="userlist" border style="width: 100%">
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column
          label="用户名"
          prop="username"
          width="110px"
        ></el-table-column>
        <el-table-column label="电子邮箱" prop="email" width="180px">
        </el-table-column>
        <el-table-column label="联系电话" prop="mobile" width="150px">
        </el-table-column>
        <el-table-column label="角色" prop="role_name" width="150px">
        </el-table-column>
        <el-table-column label="状态" prop="mg_state" width="120px">
          <template slot-scope="scope">
            <el-tooltip
              :content="'' + scope.row.mg_state"
              placement="top"
              :enterable="false"
            >
              <el-switch
                v-model="scope.row.mg_state"
                @change="handleStateChange(scope.row)"
              >
              </el-switch>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">

            <el-button
              type="primary"
              size="mini"
              round
              icon="el-icon-edit"
              @click="showEditDialog(scope.row.id)"
              >编辑</el-button
            >

            <el-button
              type="danger"
              size="mini"
              round
              icon="el-icon-delete"
              @click="handleDelete(scope.row.id)"
              >删除</el-button>

            <el-button
              type="warning"
              icon="el-icon-setting"
              round
              size="mini"
              @click="showSetRoleDialog(scope.row)"
              >分配角色</el-button>


          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="40%" @close="handleDialogClose()">
      <!-- 添加用户的内容主体区域 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="120px"
      >
        <el-form-item label="用户名：" prop="username">
          <el-input v-model="addForm.username" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="密码：" prop="password">
          <el-input
            type="password"
            v-model="addForm.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="电子邮箱：" prop="email">
          <el-input
            type="email"
            v-model="addForm.email"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="联系电话：" prop="mobile">
          <el-input v-model="addForm.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser()">确 定</el-button
        >
      </span>
    </el-dialog>

    <el-dialog title="修改用户信息" :visible.sync="dialogVisible1" width="40%" @close="editDialogClosed()">
      <!-- 修改用户信息的内容主体区域 -->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="120px"
      >
        <el-form-item label="用户名：">
          <el-input disabled v-model="editForm.username" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="电子邮箱：" prop="email">
          <el-input
            type="email"
            v-model="editForm.email"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="联系电话：" prop="mobile">
          <el-input v-model="editForm.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible1 = false">取 消</el-button>
        <el-button type="primary" @click="editUser()">确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 删除提示框 -->
    <el-dialog
      title="确认删除以下用户吗?"
      :visible.sync="deleteDialogVisible"
      width="40%">
       <!-- 删除用户的内容主体区域 -->
      <el-form
        :model="deleteComfirmForm"
        ref="deleteFormRef"
        label-width="120px"
      >
        <el-form-item label="用户名：">
          <el-input disabled v-model="deleteComfirmForm.username"></el-input>
        </el-form-item>

        <el-form-item label="电子邮箱：">
          <el-input
            disabled
            type="email"
            v-model="deleteComfirmForm.email"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="联系电话：">
          <el-input disabled v-model="deleteComfirmForm.mobile" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="角色编号：">
          <el-input disabled v-model="deleteComfirmForm.rid" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="deleteUser()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色提示框 -->
    <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="40%" @close="setRoleDialogClosed()">
    
      <el-form :model="curUserInfo" label-width="120px">
        <el-form-item label="当前用户：">
          <el-input disabled v-model="curUserInfo.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="当前角色：">
          <el-input disabled v-model="curUserInfo.role_name" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="分配新角色" >
          <el-select v-model="selectedRoleId" placeholder="请选择要为用户分配的角色" style="width:100%">
            <el-option 
            v-for="item in rolesList" 
            :key="item.value" 
            :label="item.roleName"
            :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>


      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRole()">确 定</el-button>
      </span>
    </el-dialog>


  </div>
</template>

<script>
export default {
  data() {
    var checkEmail = (rule, value, callback) => {
      const emailReg = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/;
      if (emailReg.test(value)) {
        return callback();
      }
      callback(new Error("请输入合法的电子邮箱"));
    };

    var checkMobile = (rule, value, callback) => {
      const emailReg = /^1(?:3\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8\d|9\d)\d{8}$/;
      if (emailReg.test(value)) {
        return callback();
      }
      callback(new Error("请输入合法的联系电话"));
    };

    return {
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
      userlist: [],
      total: 0,

      dialogVisible: false,
      dialogVisible1:false,
      deleteDialogVisible: false,
      setRoleDialogVisible:false,
      // addFormInfo:{},

      addForm: {},

      editForm: {},
      deleteComfirmForm: {},

      addFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "用户名长度应为3到10个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 3,
            max: 6,
            message: "密码长度应为3到6个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入电话号码", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },

      editFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "用户名长度应为3到10个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入电话号码", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      curUserInfo:{},
      rolesList:[],
      selectedRoleId:''

    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo,
      });
      // console.log(res);
      if (res.meta.status !== 200) return this.$message.error(this.meta.msg);
      this.userlist = res.data.users;
      this.total = res.data.total;
    },
    handleSizeChange(newSize) {
      // console.log(newSize);
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    handleCurrentChange(newPage) {
      // console.log(newPage);
      this.queryInfo.pagenum = newPage;
      this.getUserList();
    },
    async handleStateChange(userInfo) {
      // console.log(userInfo);
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      );
      // console.log(res);
      if (res.meta.status !== 200) {
        // 修改失败，将页面还原成修改前的值，并弹出提示
        userInfo.mg_state = !userInfo.mg_state;
        return this.$message.error(res.meta.msg);
      }
      this.$message.success(res.meta.msg);
    },
    // 监听添加用户对话框关闭的事件
    handleDialogClose(){
      this.addForm = {};
      this.$refs.addFormRef.resetFields();
    },
    
    addUser(){
      this.$refs.addFormRef.validate(async (valid) => {
        // console.log(valid);
        if(!valid) return this.$message.error('添加信息校验失败');
        const { data : res} = await this.$http.post('users', this.addForm);
        // console.log(res);
        if(res.meta.status !== 201){
          return this.$message.error('添加用户失败');
        }
        this.$message.success('添加用户成功');
        this.dialogVisible = false;
        this.getUserList();
      })
    },
    async showEditDialog(id){
      this.dialogVisible1 = true;
      // console.log(id);
      const { data: res} = await this.$http.get('users/'+ id);
      if(res.meta.status !== 200) return this.$message.error('查询用户信息失败');
      this.editForm = res.data;
    },
    editDialogClosed(){
      this.$refs.editFormRef.resetFields();
    },
    editUser(){
      this.$refs.editFormRef.validate(async (valid)=>{
        if(!valid) return this.$message.error('修改信息校验失败');
        
        const { data: res} = await this.$http.put('users/' + this.editForm.id, { email:this.editForm.email, mobile:this.editForm.mobile});
        // console.log(res);
        if(res.meta.status !== 200) return this.$message.error(res.meta.msg);
        this.$message.success(res.meta.msg);
        this.dialogVisible1 = false;
        this.getUserList();
      })
    },
    async handleDelete(id){
      this.deleteDialogVisible = true;
      const {data:res} = await this.$http.get('users/' + id);
      this.deleteComfirmForm = res.data;
    },
    async deleteUser(){
      const {data:res} = await this.$http.delete('users/' + this.deleteComfirmForm.id);
      if(res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.deleteDialogVisible = false;
      this.getUserList();
      this.$message.success(res.meta.msg);
    },
    async showSetRoleDialog(role){
      this.curUserInfo = role;
      const {data:res} = await this.$http.get('roles');
      if(res.meta.status !== 200) return this.$message.error('角色列表获取失败');
      this.rolesList = res.data;
      this.setRoleDialogVisible = true;
    },
    async setRole(){
      if(!this.selectedRoleId) return this.$message.error('请选择要分配的角色');
      const {data:res} = await this.$http.put(`users/${this.curUserInfo.id}/role`, {rid: this.selectedRoleId});
      if(res.meta.status !== 200) return this.$message.error('分配角色失败');
      this.getUserList();
      this.setRoleDialogVisible = false;
      this.$message.success('分配角色成功');
    },
    setRoleDialogClosed(){
      this.selectedRoleId = '';
    }

  },
};
</script>

<style lang="less" scoped>
.el-table {
  margin: 20px 0 20px 0;
}

.el-form {
  margin-right: 30px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-right: 30px;
}
</style>
